import java.io.IOException;
import java.net.*;
import java.util.Scanner;

/**
 * Creat with IntelliJ IDEA
 * Description
 * User: mamba24
 * Date: 2022-08-06
 * Time: 14:44
 * To BE A Better Person-2020-3-2
 */
public class UdpEchoClient {
    private DatagramSocket socket=null;
    public UdpEchoClient() throws SocketException {
        //系统自动分配端口号
        socket=new DatagramSocket();
    }
    public void start() throws IOException {
        //1.让客户端从控制台读取一个数据
        Scanner sc=new Scanner(System.in);
        while(true){
            System.out.print("> ");
            String request=sc.next();
            //2.将读取到的字符串发送给服务器，构造DatagramPacket
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),request.getBytes().length, InetAddress.getByName("127.0.0.1"),8888);
            //3.将数据报发送给服务器
            socket.send(requestPacket);
            //4.从服务器读取响应数据
            DatagramPacket responsPacket=new DatagramPacket(new byte[4096],4096);
            socket.receive(responsPacket);
            //5.将响应数据读取出来，转化为字符串
            String respons=new String(responsPacket.getData(),0,responsPacket.getLength());
            System.out.printf("req:%s  resp:%s\n",request,respons);
        }
    }

    public static void main(String[] args) throws IOException {
        UdpEchoClient client=new UdpEchoClient();
        client.start();
    }
}
